/**
 * 
 */
package com.wzq.controller;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wzq.bean.RoleModel;
import com.wzq.bean.UserModel;
import com.wzq.service.UserService;
import com.wzq.util.ApiException;
import com.wzq.util.ApiResponse;
import com.wzq.util.ResponseCode;
import com.wzq.util.UtilString;

@Controller
@RequestMapping(value = "main/")
public class LoginController {
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "loginpage", method = RequestMethod.GET)
	public String login() {
		return "login";
		
	}
	
	@RequestMapping("login")
	@ResponseBody
	public ApiResponse login(String username, String password,HttpSession httpSession)throws ApiException{
		ApiResponse response = new  ApiResponse(ResponseCode.SUCC);  
		
		UserModel user = userService.getByAccount(username);
		if (user.getName().equals(username) && user.getPassword().equals(UtilString.md5(password))) {
			UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user
					.getPassword().toString());
			Subject subject = SecurityUtils.getSubject();
			subject.login(token);
		}else{
			response.setCode(ResponseCode.USER_OR_PWD_ERROR.getCode());
			response.setDesc(ResponseCode.USER_OR_PWD_ERROR.getMessage());
		}
		
		return response;
	}

	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String submit(String username, String password) {
		UserModel user = userService.getByAccount(username);
		try {
			// 如果登陆成功
			if (user.getName().equals(username) && user.getPassword().equals(UtilString.md5(password))) {
				UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user
						.getPassword().toString());
				Subject subject = SecurityUtils.getSubject();
				subject.login(token);
			}else{
				return "login";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/member/index";
	}
	
}
